import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/material.dart';
import 'package:ls_work/doctor_advice/doctor_advice_model.dart';
import 'package:ls_work/doctor_advice/response/advice_notify_type_list.dart';
import 'package:ls_work/doctor_advice/response/medical_equipment_list.dart';
import 'package:ls_work/ui/select_old_page.dart';
import 'package:ls_work/widgets/date_range/custom_date_range_picker.dart';
class AddDoctorAdviceViewModel extends BaseViewModel{

  AddDoctorAdviceViewModel(super.context);

  var model = DoctorAdviceModel();

  ///长者
  String? customerName;
  num? clientId;

  ///医疗设备
  String? equipmentName;
  num? equipmentId;

  ///频次
  String? frequencyName;
  num? frequency;

  ///频次信息
  String get frequencyRemark => frequencyRemarkList.join(",");
  List<String> frequencyRemarkList = [];

  ///事件设置
  List<HappenTimeData> happTimes = [HappenTimeData()];

  ///医嘱说明
  String? remark;

  ///适用时间
  String? startDate;
  String? endDate;

  ///消息通知
  List<String> postIdList = [];

  List<AdviceNotifyTypeList> notifyTypeList = [];

  List<MedicalEquipmentList> equipmentList = [];

  List<String> weekList = ["周一",'周二','周三','周四','周五','周六','周日'];

  List<String> monthList = [];


  Future<void> initData() async {
    showLoadingState();
    try{
      notifyTypeList =  await model.notifyTypeList();
      equipmentList =  await model.medicalEquipment();
      showContent();
    }catch(e){
      showErrorState(e.toNetError());
    }
  }

  void initWeekMonthData(){
    monthList = List.generate(31, (index){
      return '${index+1}号';
    });
  }

  @override
  void onCreated() {
    initWeekMonthData();
    super.onCreated();
    initData();
  }

  void addHappenTime(){
    if(happTimes.isNotEmpty&&(happTimes.last.startTime.isNullOrEmpty()&&happTimes.last.endTime.isNullOrEmpty())){
      showToast("请先设置时间");
      return;
    }
    happTimes.add(HappenTimeData());
    notifyListeners();
  }

  void chooseTime(HappenTimeData happenTime,bool isStart){
    var timeStr = isStart?happenTime.startTime:happenTime.endTime;
    var current = timeStr?.toDate();
    var format = ['HH',':','nn'];
    DatePicker.showTimePicker(context,currentTime: current,onConfirm: (date){
      if(isStart){
        happenTime.startTime = date!.toDateStr(format);
      }else{
        happenTime.endTime = date!.toDateStr(format);
      }
      notifyListeners();
    });
  }

  void chooseEquipment(){
    var current = equipmentId==null?null:equipmentList.firstWhere((e)=>e.id==equipmentId);
    DataPickerView(context, equipmentList,currentFirstData: current,onSubmitListener: (p1,p2,p3){
      var item = equipmentList[p1];
      equipmentId = item.id;
      equipmentName = item.itemName;
      notifyListeners();
    }).show();
  }

  void chooseUseDate(){
    var format = [yyyy,'-',mm,'-',dd];
    showCustomDateRangePicker(
      context,
      dismissible: true,
      minimumDate: DateTime.now().subtract(const Duration(days: 30)),
      maximumDate: DateTime.now().add(const Duration(days: 100)),
      endDate: endDate?.toDate(),
      startDate: startDate?.toDate(),
      backgroundColor: Colors.white,
      primaryColor: Colors.blue,
      onApplyClick: (start, end) {
        startDate = start.toDateStr(format) ?? "";
        endDate = end.toDateStr(format) ?? "";
        notifyListeners();

      },
      onCancelClick: () {},
    );  }

  void chooseFrequency(){
    var items = [
      ChooseFrequency(itemName: '每天',id: 1),
      ChooseFrequency(itemName: '每周',id: 2),
      ChooseFrequency(itemName: '每月',id: 3),
      ChooseFrequency(itemName: '每年',id: 4),
      ChooseFrequency(itemName: '必要时',id: 5),
    ];
    var current = frequency==null?null:items.firstWhere((e)=>e.id==frequency);
    DataPickerView(context, items,currentFirstData: current,onSubmitListener: (p1,p2,p3){
      var item = items[p1];
      if(item.id!=frequency){
        frequency = item.id;
        frequencyName = item.itemName??"";
        frequencyRemarkList.clear();
        notifyListeners();
      }
    }).show();
  }

  void notifyTypeClick(String typeId){
    if(postIdList.contains(typeId)){
      postIdList.remove(typeId);
    }else{
      postIdList.add(typeId);
    }
    notifyListeners();
  }

  void chooseElder(){
    Go().push(SelectOldPage((old){
      Go().pop();
      clientId = old.id;
      customerName = old.name;
      notifyListeners();
    }));
  }
  
  void addYearFrequency(){
    var format = ['mm','-','dd'];
    DatePicker.showDatePicker(context,onConfirm: (date){
      var time = date!.toDateStr(format);
      if(frequencyRemarkList.contains(time)){
        showToast('日期重复');
      }else{
        frequencyRemarkList.add(time);
      }
      notifyListeners();
    });
  }

  Future<void> submitCreate() async {
    if(clientId==null){
      showToast("请选择长者");
      return;
    }
    if(frequency==null){
      showToast("请选择频次");
      return;
    }

    if(frequency==2&&frequencyRemarkList.isEmpty){
      showToast("请选择每周频次");
      return;
    }
    if(frequency==3&&frequencyRemarkList.isEmpty){
      showToast("请选择每月频次");
      return;
    }
    if(frequency==4&&frequencyRemarkList.isEmpty){
      showToast("请选择每年频次");
      return;
    }

    happTimes.removeWhere((e)=>e.startTime.isNullOrEmpty()&&e.endTime.isNullOrEmpty());

    var map = {
      "appointmentId":"",
      "clientId":clientId,
      "endDate":endDate,
      "id":"",
      "postId":postIdList.join(","),
      "remark":remark,
      "startDate":startDate,
      "typeId":"8",
      "aoBean":{
        "equipmentId":equipmentId,
        "frequency":frequency,
        "frequencyRemark":frequencyRemark,
        "frequencyRemarkList":frequencyRemarkList,
        "happTimes":happTimes.map((e)=>e.toJson()).toList()
      }
    };

    showLoadingDialog(msg: '提交中...');
    try{
      await model.saveAdvice(map);
      hideDialog();
      showToast('保存成功');
      finish(data: true);
    }catch(e){
      hideDialog();
      showToast(e.toNetError());
    }
  }
}

class HappenTimeData{
  String? startTime;
  String? endTime;

  HappenTimeData({
    this.startTime,
    this.endTime,
  });

  factory HappenTimeData.fromJson(Map<String, dynamic> json) {
    return HappenTimeData(
      startTime: json['startTime'],
      endTime: json['endTime'],
    );
  }

  Map<String, dynamic> toJson() => {
        'startTime': startTime,
        'endTime': endTime,
      };
}

class ChooseFrequency extends IPickerData{
  String? itemName;
  num? id;

  ChooseFrequency({this.itemName, this.id});

  @override
  String get name => itemName??"";
}